﻿using System;
using System.Linq;
using System.Web.Mvc;
using Account.IService.Entry;
using System.Configuration;
using System.Web;
using FrontCenter.Models;
using Framework.Common.Event;
using Framework.MVC;
using FrontCenter.Expand;
using Framework.Extention.Billing.Entry;
using Framework.Common.Utils;
using Extention.IService.Entry;
using System.Collections.Generic;
using Framework.Common.Entry;
using System.Text;

namespace FrontCenter.Controllers
{
    public class OrderController : AsyncControllerBase
    {
        #region Filed

        private readonly static string m_user_resource = ConfigurationManager.AppSettings["user_resource"];
        private readonly static string m_vc_resource = ConfigurationManager.AppSettings["verifycode_resource"];
        private const string m_default = "Default";
        private const string m_resource = "verifycode";

        #endregion Filed

        #region temp

        private readonly static string m_order_done = ConfigurationManager.AppSettings["OrderDone"];
        private readonly static string m_done = ConfigurationManager.AppSettings["Done"];

        private readonly static string[] m_array = new string[] { "p1_MerId", "r0_Cmd", "r1_Code", "r2_TrxId", "r3_Amt", "r4_Cur", "r5_Pid", "r6_Order", "r7_Uid", "r8_MP", "r9_BType", "hmac" };

        #endregion temp

        #region Index

        public void IndexAsync(string code,string game)
        {
            if (!string.IsNullOrWhiteSpace(game))
            {
                ViewData["game"] = game.Replace("'", "");
            }
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user != null && !string.IsNullOrWhiteSpace(user.Value) ? user.Value : null;
            if (string.IsNullOrWhiteSpace(current))
                return;

            GetAccountModel model = new GetAccountModel
            {
                IdentityCode = current,
                Source = Request.UserHostAddress,
                AccountResource = m_default
            };
            ViewData["code"] = current;
            InitModel(model);
        }

        public ActionResult IndexCompleted(string name) {
            ViewData["name"] = name;
            return View();
        }

        #endregion Index

        #region New

        public void NewAsync(string name, string source, decimal amount, string verifycode)
        {
            HttpCookie verify = Request.Cookies[m_resource];

            NewOrderModel model = new NewOrderModel{
                AccountName = name,
                OrderAmount = amount,
                OrderSource = source,
                VerifyValue = verifycode,
                VerifyCode = verify != null ? verify.Value : null,
                Resource="Normal",
                Source = Request.UserHostAddress,
                AccountResource = "Default"
            };
            InitModel(model);
        }

        public ActionResult NewCompleted(string code, string error)
        {
            return Json(string.IsNullOrWhiteSpace(error)?code:error);
        }

        #endregion New

        #region Confirm

        public void ConfirmAsync(string code, string source, string type)
        {
            ConfirmOrderModel model = new ConfirmOrderModel
            {
                OrderCode = code,
                OrderSource = source,
                Type = type,
                Source = Request.UserHostAddress
            };
            InitModel(model);
        }

        public ActionResult ConfirmCompleted(string identity,Extention.IService.Entry.OrderEntry order, string account, decimal exchange, BillingEntry billing)
        {
            if (order == null || string.IsNullOrWhiteSpace(account) || billing == null || exchange <= 0)
                return RedirectToAction("Index", string.IsNullOrWhiteSpace(identity) ? null : new System.Web.Routing.RouteValueDictionary { { "code", identity } });

            ViewData["amount"] = order.amount;
            //ViewData["code"] = order.orderCode;
            ViewData["name"] = account;
            ViewData["exchange"] = exchange;
            ViewData["billing"] = billing;
            return View();
        }

        #endregion Confirm

        #region Return

        public void ReturnAsync(string type,string source)
        {
            this.InitAccount("name");

            ReturnOrderModel model = new ReturnOrderModel
            {
                Source = Request.UserHostAddress,
                Params = Request.HttpMethod == "POST" ? HttpHelper.GetParams(Request.Form) : HttpHelper.GetParams(Request.QueryString),
                Type = type
            };
            InitModel(model);
        }

        public ActionResult ReturnCompleted(bool result, string code)
        {
            HttpCookie usercookies = Request.Cookies[m_user_resource];
            ViewData["code"] = usercookies == null ? string.Empty : usercookies.Value;
            ViewData["result"] = result;
            ViewData["ordercode"] = code;
            return View();
        }

        #endregion Return

        #region QueryPage

        public void QueryPageAsync(int? size, int? page,string source,string begin,string end,string code)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user != null && !string.IsNullOrWhiteSpace(user.Value) ? user.Value : null;
            if (string.IsNullOrWhiteSpace(current))
            {
                ViewData["error"] = true;
                return;
            }
            QueryPageOrderModel model = new QueryPageOrderModel
            {
                IdentityCode = current,
                Source = Request.UserHostAddress,
                OrderSource = source,
                OrderBegin = begin,
                OrderEnd = end,
                OrderPage = page ==null||page.Value <= 0 ? 1 : page.Value,
                OrderSize = size==null||size.Value <= 0 || size.Value > 10 ? 10 : size.Value
            };
            ViewBag.code = current;
            this.InitAccount("name");
            InitModel(model);
            this.InitConfig<IDictionary<string, KeyValueEntry<string, decimal>>>("data:order:source", (controller, dictionary) =>
            {
                ViewData["source"] = dictionary;
            });
            this.InitConfig<IDictionary<byte, object>>("data:order:status", (controller, dictionary) =>
            {
                ViewData["orderstatus"] = dictionary;
            });
            
        }

        public ActionResult QueryPageCompleted(int size, int page, int count, OrderEntry[] list,string error)
        {
            if (!string.IsNullOrWhiteSpace(error) && error.Equals("identity")) {
                  return RedirectToAction("QueryPage");
            }
            if (list != null)
            {
                ViewData["list"] = list.OrderByDescending(item => DateTime.Parse(item.indate));
            }
            if (size == 0)
            {
                ViewBag.error = true;
            }
            else {
                ViewBag.Status = "login";
            }
            ViewData["count"] = count;
            return View();
        }

        #endregion QueryPage

        #region End

        public void EndAsync(string type,string source)
        {
            EndOrderModel model = new EndOrderModel
            {
                Source = Request.UserHostAddress,
                Params = HttpHelper.GetParams(Request.Form),
                OrderSource = source,
                Type = type
            };

            InitModel(model);
        }

        public ActionResult EndCompleted(bool result, string content)
        {
            return Content(result ? content : string.Empty);
        }

        #endregion End

        #region Distribute

        public ActionResult Distribute(string type, string source)
        {
            StringBuilder paramstr = new StringBuilder();
            foreach (var key in m_array)
            {
                paramstr.AppendFormat(paramstr.Length <= 0 ? "{0}={1}" : "&{0}={1}", key, GetQueryString(key, Request.Url.Query, '&'));
            }

            string order = Request.Params["r1_Code"];
            string mode = Request.Params["r9_BType"];

            string content = string.Empty;
            if (string.Equals(order, "1") && string.Equals(mode, "2"))
            {
                content = RechargeHelper.Distribute(string.Format(m_order_done, type, source), "POST", paramstr.ToString());
            }
            else
            {
                content = RechargeHelper.Distribute(string.Format(m_done,type, source), "POST", paramstr.ToString());
            }

            return Content(content);
        }

        #endregion Distribute

        #region Private

        private static string GetQueryString(string strParaName, string strUrl, char strSplitChar)
        {
            string result = "";

            string[] strUrlArg = strUrl.Split(strSplitChar);

            for (int i = 0; i < strUrlArg.Length; i++)
            {
                if (strUrlArg[i].IndexOf(strParaName) >= 0)
                {
                    result = System.Web.HttpUtility.UrlDecode(strUrlArg[i].Split('=')[1], System.Text.Encoding.GetEncoding("gb2312"));
                    break;
                }
            }
            return result;
        }

        #endregion Private

        

    }
}
